import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:jtlf/contacts/friend_list.dart';

class ContactsPage extends StatefulWidget {
  @override
  _ContactsPageState createState() => _ContactsPageState();
}

class _ContactsPageState extends State<ContactsPage> {
  final TextEditingController _searchController = TextEditingController();
  final List<Department> _departments = [
    Department(
      name: '阿里巴巴集团',
      members: [
        Employee(name: '张勇', position: 'CEO', avatar: 'https://example.com/ceo.png'),
      ],
      children: [
        Department(
          name: '技术部',
          members: [
            Employee(name: '王强', position: 'CTO', avatar: 'https://example.com/cto.png'),
            Employee(name: '李娜', position: '架构师', avatar: 'https://example.com/arch.png'),
          ],
          children: [
            Department(
              name: '前端组',
              members: [
                Employee(name: '陈小明', position: '前端工程师', avatar: 'https://example.com/fe.png'),
              ],
            ),
          ],
        ),
      ],
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('通讯录'),
        actions: [
          IconButton(icon: Icon(Icons.add), onPressed: () {}),
        ],
      ),
      body: Column(
        children: [
          _buildSearchBar(),
          Expanded(
            child: CustomScrollView(
              slivers: [
                _buildQuickAccess(),
                _buildOrgStructure(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSearchBar() {
    return Padding(
      padding: EdgeInsets.all(12),
      child: TextField(
        controller: _searchController,
        decoration: InputDecoration(
          hintText: '搜索',
          prefixIcon: Icon(Icons.search),
          filled: true,
          fillColor: Colors.grey[100],
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(20),
            borderSide: BorderSide.none,
          ),
        ),
      ),
    );
  }

  Widget _buildQuickAccess() {
    return SliverToBoxAdapter(
      child: Container(
        height: 100,
        child: ListView(
          scrollDirection: Axis.horizontal,
          children: [
            _buildQuickItem('我的客户', Icons.people_alt),
            _buildQuickItem('外部联系人', Icons.business_center),
            _buildQuickItem('常用联系人', Icons.star),
          ],
        ),
      ),
    );
  }

  Widget _buildQuickItem(String title, IconData icon) {
    // return Container(
    //   width: 100,
    //   child: Column(
    //     mainAxisAlignment: MainAxisAlignment.center,
    //     children: [
    //       CircleAvatar(
    //         radius: 28,
    //         child: Icon(icon, size: 30),
    //         backgroundColor: Colors.grey[100],
    //       ),
    //       SizedBox(height: 8),
    //       Text(title, style: TextStyle(fontSize: 12)),
    //     ],
    //   ),
    // );
    return InkWell(
      onTap: () => Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => FriendListWidget(),
        ),
      ),
      borderRadius: BorderRadius.circular(12), // 匹配圆角
      child: Container(
        width: 100,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircleAvatar(
              radius: 28,
              child: Icon(icon, size: 30),
              backgroundColor: Colors.grey[100],
            ),
            SizedBox(height: 8),
            Text(title, style: TextStyle(fontSize: 12)),
          ],
        ),
      ),
    );
  }

  Widget _buildOrgStructure() {
    return SliverList(
      delegate: SliverChildBuilderDelegate(
            (context, index) => _buildDepartment(_departments[index]),
        childCount: _departments.length,
      ),
    );
  }

  Widget _buildDepartment(Department department) {
    return DepartmentWidget(
      department: department,
      onTap: () => _toggleDepartment(department),
    );
  }

  void _toggleDepartment(Department department) {
    setState(() => department.isExpanded = !department.isExpanded);
  }
}

class DepartmentWidget extends StatefulWidget {
  final Department department;
  final VoidCallback onTap;

  const DepartmentWidget({required this.department, required this.onTap});

  @override
  _DepartmentWidgetState createState() => _DepartmentWidgetState();
}

class _DepartmentWidgetState extends State<DepartmentWidget> {
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ListTile(
          leading: Icon(Icons.account_tree, color: Colors.grey),
          title: Text(widget.department.name),
          trailing: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text('${widget.department.members.length + _totalMembers(widget.department)}'),
              Icon(widget.department.isExpanded ? Icons.expand_less : Icons.expand_more),
            ],
          ),
          onTap: widget.onTap,
        ),
        if (widget.department.isExpanded) ...[
          ...widget.department.children.map(_buildDepartment),
          ...widget.department.members.map(_buildEmployee),
        ],
      ],
    );
  }

  Widget _buildDepartment(Department department) {
    return DepartmentWidget(
      department: department,
      onTap: () => _toggleDepartment(department),
    );
  }

  void _toggleDepartment(Department department) {
    setState(() => department.isExpanded = !department.isExpanded);
  }

  Widget _buildEmployee(Employee employee) {
    return ListTile(
      leading: Stack(
        children: [
          CircleAvatar(
            backgroundImage: CachedNetworkImageProvider(employee.avatar),
          ),
          Positioned(
            right: 0,
            bottom: 0,
            child: Container(
              width: 12,
              height: 12,
              decoration: BoxDecoration(
                color: Colors.green,
                shape: BoxShape.circle,
                border: Border.all(color: Colors.white, width: 2),
              ),
            ),
          ),
        ],
      ),
      title: Text(employee.name),
      subtitle: Text(employee.position),
      trailing: Icon(Icons.chat_bubble_outline),
      onTap: () => _showEmployeeDetail(employee),
    );
  }

  int _totalMembers(Department department) {
    return department.children.fold(0, (sum, child) => sum + child.members.length + _totalMembers(child));
  }

  void _showEmployeeDetail(Employee employee) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(employee.name),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            CircleAvatar(
              radius: 40,
              backgroundImage: CachedNetworkImageProvider(employee.avatar),
            ),
            SizedBox(height: 12),
            Text(employee.position),
          ],
        ),
      ),
    );
  }
}

// 数据模型
class Department {
  String name;
  List<Employee> members;
  List<Department> children;
  bool isExpanded;

  Department({
    required this.name,
    this.members = const [],
    this.children = const [],
    this.isExpanded = false,
  });
}

class Employee {
  final String name;
  final String position;
  final String avatar;

  Employee({
    required this.name,
    required this.position,
    required this.avatar,
  });
}

// 在ContactsPage类中添加右侧字母索引
// Widget build(BuildContext context) {
//   return Stack(
//     children: [
//       // 原有布局...
//       _buildIndexBar(),
//     ],
//   );
// }
//
// Widget _buildIndexBar() {
//   return Align(
//     alignment: Alignment.centerRight,
//     child: Container(
//       padding: EdgeInsets.symmetric(vertical: 12),
//       child: Column(
//         mainAxisSize: MainAxisSize.min,
//         children: [
//           _buildIndexChar('★'),
//           _buildIndexChar('A'),
//           _buildIndexChar('B'),
//           // 更多字母...
//         ],
//       ),
//     ),
//   );
// }
//
// Widget _buildIndexChar(String char) {
//   return GestureDetector(
//     onTap: () => _scrollToIndex(char),
//     child: Text(char, style: TextStyle(fontSize: 12)),
//   );
// }
